//
//  NewworkViewController.m
//  jiaxingOASystem
//
//  Created by michael on 16/6/12.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "huodongTableViewCell.h"
#import "PayTypeModel.h"
#import "OASelectDepartmentController.h"
#import "NotonewsViewController.h"
#import "NewworkViewController.h"
#import "OADetailCell.h"
#import "selectview.h"
#import "MHDatePicker.h"
#import "GDataDefines.h"
//#import "createDocmodel.h"
#import "OADepartmentModel.h"
#import "OADetailDispatchModel.h"
#import "huiyiViewController.h"

#import "chuguoViewController.h"
@interface chuguoViewController (){

    NSMutableArray *indexPaths;
}


@property(nonatomic,strong)NSMutableArray * departments;//发送
@property(nonatomic,strong)NSMutableArray * department;//保存

@property(nonatomic,copy)NSString * infoString; //服务器返回字段 根据该字段跳转不同的界面
@property(nonatomic,copy)NSString * infoString0;
@property(nonatomic,strong)NSMutableArray * subItems;  //选中 需要提交得数据
@property(nonatomic,strong)OADetailDispatchModel * detailModel ;

@property (strong, nonatomic)selectview * selectview;
@property (strong, nonatomic)UIButton * button1;
@property (strong, nonatomic)UIButton * button2;
@property (strong, nonatomic)UIButton * databutton;
@property (strong, nonatomic)UIButton * daybutton;
//@property (strong, nonatomic)  UITextField *TextField1;
@property (strong, nonatomic)  UITextView *renshuField;
@property (strong, nonatomic)  UITextView *mingcengField;
@property (strong, nonatomic)  UITextView *dianhuaField;
//@property (strong, nonatomic)  UITextView *mingcengField;
@property (strong, nonatomic)  UITextView *guojiaField;
@property (strong, nonatomic)  UITextView *didianField;
@property (strong, nonatomic)  UITextView *xingmingField;

@property (strong, nonatomic)  UITextView *tianshuField;
@property (strong, nonatomic)  UITextView *zhiweiField;




@property (strong, nonatomic)  UITextView *personField;

@property (strong, nonatomic)  UITextView *dayField;

@property (strong, nonatomic)  UITextView *workField;
@property (strong, nonatomic)  UITextView *chuguoField;
@property (strong, nonatomic)  UITextView *TextField1;
@property (strong, nonatomic)  UITextView *beifenField;
@property(nonatomic,copy)NSString * body;
@property (strong, nonatomic) MHDatePicker *selectDatePicker;

@property(nonatomic,copy)NSString * typestring;

@property(nonatomic,copy)NSString * shifoustring;
@property(nonatomic,copy)NSString * timebeforestring;
@property(nonatomic,copy)NSString * timeafterstring;
@property(nonatomic,copy)NSString * timestring;//时间

@property(nonatomic,copy)NSString * datastring;//日期

@property(nonatomic,copy)NSString * tianshutring;//日期

@property(nonatomic,copy)NSString * zhiwustring;//职务

//办公室
@property (nonatomic,copy)NSString *renshustring;
@property (nonatomic,copy)NSString *bumenstring;
@property (nonatomic,copy)NSString *dianhuatring;
@property (nonatomic,copy)NSString *mingcengtring;
@property (nonatomic,copy)NSString *guojiastring;
@property (nonatomic,copy)NSString *chuguogtring;
@property (nonatomic,copy)NSString *didiantring;
@property (nonatomic,copy)NSString *nametring;
@property (nonatomic,copy)NSString *beifentring;

@property (nonatomic,copy)NSString *shiyoustring;
@property (nonatomic,copy)NSString *personstring;
@property (nonatomic,copy)NSString *daystring;

// 按钮
@property (nonatomic,copy)NSString *anniu;

@end

@implementation chuguoViewController
-(NSMutableArray*)subItems{
    if (_subItems ==nil) {
        _subItems = [NSMutableArray array];
    }
    return _subItems;

}

- (void)viewDidLoad {
    [super viewDidLoad];
     NSDate *currentDate = [NSDate date];//获取当前时间，日期
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd "];
_datastring = [dateFormatter stringFromDate:currentDate];
   indexPaths = [[NSMutableArray alloc] init];

 
    [self _initView];
    [self requestdata];
    self.view.backgroundColor = [UIColor whiteColor];
    //点击手势
 UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(keybordDown)];
    [self.view addGestureRecognizer:tap];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(btnClick:) name:@"2" object:nil];
    
 UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStyleDone target:self action:@selector(tianjiaaction)];
    self.navigationItem.rightBarButtonItem = barButtonItem;
}
- (void)tianjiaaction{
    PayTypeModel *typeM = [[PayTypeModel alloc] init];
       [indexPaths addObject:typeM];
       [_tableView reloadData];
//NSIndexPath *indexpath = [NSIndexPath indexPathForRow:6+indexPaths.count inSection:0];
//[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObjects:indexpath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];


}
- (void)btnClick:(NSNotification *)noti{

NSString *str = noti.userInfo[@"text"];
_anniu = str;
}


- (void)keybordDown {


    [self.view endEditing:YES];
        }
- (void)requestdata{
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId}];
    [HttpTools postWithURL:KexchdataURL arrays:array method:@"createDoc" success:^(id JSON) {
    NSLog(@"=====%@",JSON);
   
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        self.detailModel = [self getDetailModel:JSON];
        
//        _renshustring = _detailModel.name;
//        _bumenstring = _detailModel.workname;
//        _personstring = _detailModel.person;
//        _daystring = _detailModel.data;
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];


}
//获取解析得到的数据。
-( OADetailDispatchModel *)getDetailModel:(NSString*)dataString;
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    OADetailDispatchModel * detailModel = [[OADetailDispatchModel alloc]init];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（Users）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（User）
    NSArray *rootData= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement *subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in tempArray) {
            GDataXMLElement *documentElement= [[data elementsForName:@"GwOrigUnit"] objectAtIndex:0];
//            detailModel.name = [documentElement stringValue];
//            
//            
//            
//           GDataXMLElement *filestep= [[data elementsForName:@"GwSubject"] objectAtIndex:0];
//            detailModel.workname = [filestep stringValue];
//             GDataXMLElement *filestep1= [[data elementsForName:@"GwFileClass"] objectAtIndex:0];
//            detailModel.person = [filestep1 stringValue];
//             GDataXMLElement *filestep2= [[data elementsForName:@"GwRegister"] objectAtIndex:0];
//            detailModel.data = [filestep2 stringValue];
            
            GDataXMLElement *fileId= [[data elementsForName:@"唯一标识"] objectAtIndex:0];
            detailModel.fileId = [fileId stringValue];
            
        }
    }
    
    
    
    return detailModel;
    
}

- (void)_initView{
_tableView  = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, KScreenWidth, KScreenHeight-47-64) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;

UIButton *savebutton = [UIButton buttonWithType:UIButtonTypeCustom];
[savebutton setTitle:@"保存" forState:UIControlStateNormal];
[savebutton setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
savebutton.frame = CGRectMake(0, _tableView.bottom, .5*KScreenWidth, 47);

UIButton *cilcuationbutton = [UIButton buttonWithType:UIButtonTypeCustom];
[cilcuationbutton setTitle:@"发送" forState:UIControlStateNormal];
cilcuationbutton.frame = CGRectMake(savebutton.right, _tableView.bottom, .5*KScreenWidth, 47);
[cilcuationbutton setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
savebutton.backgroundColor = [UIColor whiteColor];
cilcuationbutton.backgroundColor = [UIColor whiteColor
];
[savebutton addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
[cilcuationbutton addTarget:self action:@selector(cilcuationAction) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:savebutton];
[self.view addSubview:cilcuationbutton];
 
[self.view addSubview:_tableView];

}
- (void)saveAction{
 [self keybordDown];
    
    if ([self.mingcengField.text length] == 0) {
        [self.view makeToast:@"对不起，团组名称为空"];
        return;
    }else if ([self.renshuField.text length] == 0) {
        [self.view makeToast:@"对不起，团组人数为空"];
        return;
    }else if ([self.tianshuField.text length] == 0) {
        [self.view makeToast:@"对不起，出访天数为空"];
        return;
    }else if ([_guojiaField.text length] == 0) {
        [self.view makeToast:@"对不起，出访国家(地区)为空"];
        return;
    }else if ([_chuguoField.text length] == 0) {
        [self.view makeToast:@"对不起，年度出国次数为空"];
        return;
    }else if ([_beifenField.text length] == 0) {
        [self.view makeToast:@"对不起，备份为空"];
        return;
    }


   
else{




_timestring = [NSString stringWithFormat:@"%@到%@",_timebeforestring,_timeafterstring];
_timestring = [_timestring stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
_timestring = [_timestring stringByReplacingOccurrencesOfString:@"月" withString:@"-"];
_timestring = [_timestring stringByReplacingOccurrencesOfString:@"日" withString:@""];



NSString *json =[NSString stringWithFormat: @"{'name':'%@','personNum':'%@', 'tvDate':'%@','dayNum':'%@',country':'%@',countryNum':'%@',remark':'%@'}",_mingcengField.text,_renshuField.text,_datastring, _tianshuField.text,_guojiaField.text,_chuguoField.text,_beifenField.text];
 NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];


if (indexPaths.count) {
   _mutarray = [[NSMutableArray alloc] init];
   for (PayTypeModel *typeM in indexPaths) {
 NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    [dict setObject:[NSString stringWithFormat:@"%@",typeM.Name] forKey:@"name"];
    [dict setObject:[NSString stringWithFormat:@"%@",typeM.zhiwu] forKey:@"duty"];
    [_mutarray addObject:dict];
    
}

       _array =@[@{@"sName":userId},@{@"json":json},_mutarray];
NSLog(@"1");
}else{

    _array =@[@{@"sName":userId},@{@"json":json}];
    NSLog(@"1");

}
        [HttpTools requestWithURL:Kexchcreate arrays:_array method:@"createApprovalCar"  success:^(id JSON) {
    _infoString0 = nil;
    [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
     NSData * data = [JSON dataUsingEncoding:NSUTF8StringEncoding];
     GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    GDataXMLElement *rootElement = [doc rootElement];
      
          NSArray *infoData= [rootElement elementsForName:@"info"];
    for (int i = 0;i<[infoData count];i++)
    {
        GDataXMLElement *infoElement = [infoData objectAtIndex:i];
        self.infoString0 = [infoElement stringValue];
    }
    if ([self.infoString0 isEqualToString:@"19"]) { //成功发送，提交下一办理人
        
        [self.view.window makeToast:@"保存成功"];
       
    }
          
    else if ([self.infoString0 isEqualToString:@"1044"]){
    
    [self.view.window makeToast:@"服务器出错"];

    }else{
    
    [self.view.window makeToast:@"保存失败"];
    }
   } failure:^(NSError *error) {
        [self.view.window makeToast:@"保存失败"];
    }];
}
}
- (void)cilcuationAction{
 [self keybordDown];
    if ([self.chuguoField.text length] == 0) {
        [self.view makeToast:@"对不起，你的外出事由地点空"];
        return;
    }
else{

if ([_selectview.orderString isEqualToString:@"0"]) {
    _typestring = @"因公";
}else{
  _typestring = @"因私";
}
_timestring = [NSString stringWithFormat:@"%@到%@",_timebeforestring,_timeafterstring];
_timestring = [_timestring stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
_timestring = [_timestring stringByReplacingOccurrencesOfString:@"月" withString:@"-"];
_timestring = [_timestring stringByReplacingOccurrencesOfString:@"日" withString:@""];
self.body = [NSString stringWithFormat:@"&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n"
                     "&lt;交换 xmlns=\'exch.jhsx.gov.cn/data\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'&gt;\n"
                     "&lt;数据&gt;\n"
                     "&lt;数据要素&gt;\n"
                     "&lt;唯一标识&gt;\n"
                     "%@"
                     "&lt;/唯一标识&gt;\n"
                     "&lt;GwOrigUnit  name='姓名'&gt;\n"
                     "%@"
                     "&lt;/GwOrigUnit&gt;\n"
                     "&lt;GwSubject  name='单位'&gt;\n"
                     "%@"
                     "&lt;/GwSubject&gt;\n"
                     "&lt;GwNum  name='职务'&gt;\n"
                     "%@"
                     "&lt;/GwNum&gt;\n"
                     "&lt;GwIssueDate  name='外出类型'&gt;\n"
                     "%@"
                     "&lt;/GwIssueDate&gt;\n"
                     "&lt;GwSwClass  name='外出事由地点'&gt;\n"
                     "%@"
                     "&lt;/GwSwClass&gt;\n"
                     "&lt;swfs  name='外出时间'&gt;\n"
                     "%@"
                     "&lt;/swfs&gt;\n"
                     "&lt;GwHurry  name='销假情况'&gt;\n"
                     "%@"
                     "&lt;/GwHurry&gt;\n"
                     "&lt;sendtype  name='备注'&gt;\n"
                     "%@"
                     "&lt;/sendtype&gt;\n"
                     "&lt;GwFileClass  name='申请人'&gt;\n"
                     "%@"
                     "&lt;/GwFileClass&gt;\n"
                     "&lt;GwRegister  name='日期'&gt;\n"
                     "%@"
                     "&lt;/GwRegister&gt;\n"
                     "&lt;sendmemo  name='天数'&gt;\n"
                     "%@"
                     "&lt;/sendmemo&gt;\n"
                     "&lt;/数据要素&gt;\n"
                      "&lt;数据对照&gt;\n"
                       "&lt;/数据对照&gt;\n"
                       "&lt;正文实体&gt;\n"
                       "&lt;/正文实体&gt;\n"
                       "&lt;数据实体&gt;\n"
                       "&lt;/数据实体&gt;\n"
                     "&lt;/数据&gt;\n"
                     "&lt;/交换&gt;",
                     self.detailModel.fileId,
                     self.renshuField.text,
                     self.mingcengField.text,
                     self.workField.text,
                     self.typestring,
                        self.chuguoField.text,
                    self.timestring,
                    self.TextField1.text,
             
                     self.beifenField.text,
                     self.personField.text,
                     self.datastring,
                     self.dayField.text
                     ];
             
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    __weak typeof(self) weakSelf = self;
    NSArray * array =@[@{@"userId":_detailModel.fileId},@{@"sName":userId},@{@"formxml":self.body}];
    [HttpTools postWithURL:KexchdataURL arrays:array method:@"setSaveDoc"  success:^(id JSON) {
    _infoString0 = nil;
    [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    
     NSData * data = [JSON dataUsingEncoding:NSUTF8StringEncoding];
     GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    GDataXMLElement *rootElement = [doc rootElement];
      
          NSArray *infoData= [rootElement elementsForName:@"info"];
    for (int i = 0;i<[infoData count];i++)
    {
        GDataXMLElement *infoElement = [infoData objectAtIndex:i];
        self.infoString0 = [infoElement stringValue];
    }
     
    if ([self.infoString0 isEqualToString:@"19"]) { //成功发送，提交下一办理人
        [self.view.window makeToast:@"保存成功"];
        [self setSubmitWork];
    }
          
    else if ([self.infoString0 isEqualToString:@"1044"]){
    
    [self.view.window makeToast:@"服务器出错"];

    }else{
    
    [self.view.window makeToast:@"保存失败"];
    }
   } failure:^(NSError *error) {
        [self.view.window makeToast:@"保存失败"];
    }];
}


    


}
- (void)setSubmitWork{
    __weak typeof(self) weakSelf = self;

 NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];

 NSArray * array =@[@{@"userId":_detailModel.fileId},@{@"sName":userId},@{@"formxml":self.body}];
[HttpTools postWithURL:KexchdataURL arrays:array method:KSetSubmitWorkMethod success:^(id JSON) {
        self.departments = [self dataWith:JSON];
        
if ([self.infoString isEqualToString:@"11"]) { //成功发送，提交下一办理人
            
            [UIAlertView showWithTitle:@"提示" message:@"发送成功" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
              [self.navigationController popViewControllerAnimated:YES];
                                  }];
            
        }else if ([self.infoString isEqualToString:@"12"]) { //返回环节信息
              OASelectDepartmentController*    selectVC = [[OASelectDepartmentController alloc]init];
            selectVC.subItems = self.subItems;
            selectVC.body = self.body;
            selectVC.detailPatchModel = self.detailModel;
//            selectVC.attachmentArray = self.attachmentArray;
            selectVC.departments = self.departments;
                        selectVC.hidesBottomBarWhenPushed = YES;
            selectVC.hidesBottomBarWhenPushed = YES;

               [weakSelf.navigationController pushViewController:selectVC animated:YES];
            

        }else if ([self.infoString isEqualToString:@"13"]) {//返回人员列表
            //            OASelectPersonController * selectPersonVC = [[OASelectPersonController alloc]init];
            //            selectPersonVC.personArray = self.personArray;
            //            selectPersonVC.body = self.body;
            //            selectPersonVC.setpString = self.setpString;
            //            if (self.detailModel ) {
            //                selectPersonVC.fileId = self.detailModel.fileId;
            //            }else if (self.detailPatchModel){
            //                selectPersonVC.fileId = self.detailPatchModel.fileId;
            //            }
            //
            //            [self.navigationController pushViewController:selectPersonVC animated:YES];
      
            
            
        }else if ([self.infoString isEqualToString:@"14"]){ //返回树
            //            OASelectPersonSecondController * selectPersonVC = [[OASelectPersonSecondController alloc]init];
            //            selectPersonVC.personArray = self.personArray;
            //            selectPersonVC.body = self.body;
            //            selectPersonVC.setpString = self.setpString;
            //            if (self.detailModel ) {
            //                selectPersonVC.fileId = self.detailModel.fileId;
            //            }else if (self.detailPatchModel){
            //                selectPersonVC.fileId = self.detailPatchModel.fileId;
            //            }
            //            selectPersonVC.groupArray = self.groupArray;
            //            selectPersonVC.rowArray = self.rowArray;
            //            [self.navigationController pushViewController:selectPersonVC animated:YES];
            
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }];




}

#pragma mark 数据解析

-(NSMutableArray*)dataWith:(NSString*)dataString
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableArray *arrData = [[NSMutableArray alloc]init];
    NSMutableArray * subData = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    GDataXMLElement *rootElement = [doc rootElement];
    NSArray *users = [rootElement children];
    for (int i = 0;i<[users count];i++) {
        GDataXMLElement *ele = [users objectAtIndex:i];
        if ([[ele name] isEqualToString:@"环节"]){
            OADepartmentModel * model = [[OADepartmentModel alloc]init];
            model.department = [[ele attributeForName:@"流向"] stringValue];
            for (int j=0; j<[ele childCount]; j++) {
                GDataXMLElement  *subItem = [ele childAtIndex:j];
                [subData addObject:subItem.stringValue];
            }
            [arrData addObject:model];
        }
    }
    self.subItems = subData; //选中 需要提交得数据
    NSArray *infoData= [rootElement elementsForName:@"info"];
    for (int i = 0;i<[infoData count];i++)
    {
        GDataXMLElement *infoElement = [infoData objectAtIndex:i];
        self.infoString = [infoElement stringValue];
    }
    
    return arrData;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 7+indexPaths.count;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{


   if (indexPath.row==0) {

  static NSString *cellid0 = @"cell0";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid0];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid0];
           UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];

  label.text = @"团组名称 :";
    
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _mingcengField = [[UITextView alloc]init];
      _mingcengField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _mingcengField.backgroundColor = myColor;
 [_mingcengField setFont:[UIFont systemFontOfSize:13]];
 _mingcengField.textAlignment = NSTextAlignmentLeft;
      _mingcengField.delegate = self;
       [cell.contentView addSubview:_mingcengField];
       }
               _mingcengField.text = _mingcengtring;

             return cell;

}
else if (indexPath.row==1) {
 static NSString *cellid1 = @"cell1";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid1];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid1];
          UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
        
      label.text = @"团组人数 :";
    
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _renshuField = [[UITextView alloc]init];
      _renshuField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _renshuField.backgroundColor = myColor;
 [_renshuField setFont:[UIFont systemFontOfSize:13]];
 _renshuField.textAlignment = NSTextAlignmentLeft;
      _renshuField.delegate = self;
       [cell.contentView addSubview:_renshuField];
       }
               _renshuField.text = _renshustring;

             return cell;
}
else if (indexPath.row==2) {
static NSString *cellid2 = @"cell2";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid2];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid2];
      UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
       label.text = @"出访日期 :";
    
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
 _databutton = [UIButton buttonWithType:UIButtonTypeCustom];
      _databutton.frame = CGRectMake(label.right, label.top, 120, label.height);
//    _button1.backgroundColor = [UIColor yellowColor];
    _databutton.titleLabel.font = [UIFont systemFontOfSize: 13.0];
    
                 [_databutton setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
           [_databutton addTarget:self action:@selector(dataaction) forControlEvents:UIControlEventTouchUpInside];

 
       [cell.contentView addSubview:_databutton];
       }
             [_databutton setTitle:_datastring forState:UIControlStateNormal];


             return cell;
}

else if (indexPath.row==3) {
    static NSString *cellid3 = @"cell3";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid3];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid3];
      UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
    label.text = @"出访天数 :";
    
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _tianshuField = [[UITextView alloc]init];
      _tianshuField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _tianshuField.backgroundColor = myColor;
 [_tianshuField setFont:[UIFont systemFontOfSize:13]];
 _tianshuField.textAlignment = NSTextAlignmentLeft;
      _tianshuField.delegate = self;
       [cell.contentView addSubview:_tianshuField];
       }
               _tianshuField.text = _tianshutring;

             return cell;

}
else if (indexPath.row==4) {
 static NSString *cellid4 = @"cell4";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid4];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid4];
         UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
    label.text = @"出访国家(地区) :";
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _guojiaField = [[UITextView alloc]init];
      _guojiaField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _guojiaField.backgroundColor = myColor;
 [_guojiaField setFont:[UIFont systemFontOfSize:12]];
      _guojiaField.delegate = self;
       [cell.contentView addSubview:_guojiaField];
       }
//             _guojiaField.text = _guojiastring;

             return cell;




}else if (indexPath.row==5) {
static NSString *cellid5 = @"cell5";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid5];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid5];
              UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];

      label.text = @"年度出国次数 :";
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _chuguoField = [[UITextView alloc]init];
      _chuguoField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _chuguoField.backgroundColor = myColor;
 [_chuguoField setFont:[UIFont systemFontOfSize:12]];
      _chuguoField.delegate = self;
       [cell.contentView addSubview:_chuguoField];
       }
//             _chuguoField.text = _chuguogtring;

             return cell;
}else if (indexPath.row==6) {
static NSString *cellid6 = @"cell6";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid6];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid6];
      UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
       label.text = @"备份 :";
    _beifenField.keyboardType = UIKeyboardTypeDecimalPad;

        label.numberOfLines = 0;

    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _beifenField = [[UITextView alloc]init];
      _beifenField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
//          _beifenField.keyboardType = UIKeyboardTypeDecimalPad;

      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _beifenField.backgroundColor = myColor;
 [_beifenField setFont:[UIFont systemFontOfSize:12]];
      _beifenField.delegate = self;
       [cell.contentView addSubview:_beifenField];
       }
//       _beifenField.text = _beifentring;
             return cell;
}


else {

static NSString *cellid9 = @"cell9";
    huodongTableViewCell *cell = (huodongTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid9];
    if (!cell) {
        cell=[[huodongTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid9];
        
//    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 40)];
//    label.text = @"预报人员姓名 :";
//    label.numberOfLines = 0;
//    label.font = [UIFont systemFontOfSize:14];
//    [cell.contentView addSubview:label];
//     UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(10, label.bottom, 100, 40)];
//    label2.text = @"在外职位 :";
//    label2.numberOfLines = 0;
//    label2.font = [UIFont systemFontOfSize:14];
//    [cell.contentView addSubview:label2];
//
//    _xingmingField = [[UITextView alloc]init];
////    _xingmingField.tag = indexPath.row-7;
//      _xingmingField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, 35);
//
//      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
//      _xingmingField.backgroundColor = myColor;
//      [_xingmingField setFont:[UIFont systemFontOfSize:12]];
//      _xingmingField.delegate = self;
//       [cell.contentView addSubview:_xingmingField];
//       
//       _zhiweiField = [[UITextView alloc]init];
////       _zhiweiField.tag = indexPath.row-7;
//      _zhiweiField.frame = CGRectMake(label.right, label.bottom+10, KScreenWidth-120, 35);
//
//      _zhiweiField.backgroundColor = myColor;
//      [_zhiweiField setFont:[UIFont systemFontOfSize:12]];
//      _zhiweiField.delegate = self;
//       [cell.contentView addSubview:_zhiweiField];

       
       }
    
//        _xingmingField.tag = indexPath.row-7;
//
//       _zhiweiField.tag = indexPath.row-7;
cell.model = indexPaths[indexPath.row-7];
             return cell;

}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

NSLog(@"%ld",(long)indexPath.row);

}
- (void)textViewDidChange:(UITextView *)textView
{
if(textView ==_renshuField){
_renshustring = _renshuField.text;
}
if(textView ==_mingcengField){
_mingcengtring = _mingcengField.text;
}

if(textView ==_tianshuField){
_tianshutring = _tianshuField.text;
}

if(textView ==_chuguoField){
_chuguogtring = _chuguoField.text;
}
if(textView ==_xingmingField){

    PayTypeModel *typeM = indexPaths[_xingmingField.tag];
typeM.Name = _xingmingField.text;

}
if(textView ==_zhiweiField){
    PayTypeModel *typeM = indexPaths[_zhiweiField.tag];
typeM.zhiwu = _zhiweiField.text;
}
//NSLog(@"name : %@  zhiwei :%@",_nametring,_zhiwustring);
NSLog(@"name.tag : %ld  zhiwei.tag :%ld",(long)_xingmingField.tag,(long)_zhiweiField.tag);

}
- (void)action1{
 _selectDatePicker = [[MHDatePicker alloc] init];
    _selectDatePicker.isBeforeTime = YES;
    _selectDatePicker.datePickerMode = UIDatePickerModeDate;
    
    __weak typeof(self) weakSelf = self;
    [_selectDatePicker didFinishSelectedDate:^(NSDate *selectedDate) {
//        NSString *string = [NSString stringWithFormat:@"%@",[NSDate dateWithTimeInterval:3600*8 sinceDate:selectedDate]];
//        weakSelf.myLabel2.text = string;
      NSString *string = [weakSelf dateStringWithDate:selectedDate DateFormat:@"yyyy年MM月dd日"];
      _timebeforestring = string;
      [weakSelf.button1 setTitle:string forState:UIControlStateNormal];
    }];

}
- (void)dataaction{
 _selectDatePicker = [[MHDatePicker alloc] init];
    _selectDatePicker.isBeforeTime = YES;
    _selectDatePicker.datePickerMode = UIDatePickerModeDate;
    
    __weak typeof(self) weakSelf = self;
    [_selectDatePicker didFinishSelectedDate:^(NSDate *selectedDate) {
      NSString *string = [weakSelf dateStringWithDate:selectedDate DateFormat:@"yyyy年MM月dd日"];
            string = [string stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
string = [string stringByReplacingOccurrencesOfString:@"月" withString:@"-"];
string = [string stringByReplacingOccurrencesOfString:@"日" withString:@""];

      _datastring = string;
      [weakSelf.databutton setTitle:string forState:UIControlStateNormal];
    }];

}

- (void)dataaction2{
 _selectDatePicker = [[MHDatePicker alloc] init];
    _selectDatePicker.isBeforeTime = YES;
    _selectDatePicker.datePickerMode = UIDatePickerModeDate;
    
    __weak typeof(self) weakSelf = self;
    [_selectDatePicker didFinishSelectedDate:^(NSDate *selectedDate) {
      NSString *string = [weakSelf dateStringWithDate:selectedDate DateFormat:@"yyyy年MM月dd日"];
      _datastring = string;
      [weakSelf.databutton setTitle:string forState:UIControlStateNormal];
    }];

}
- (void)action2{
_selectDatePicker = [[MHDatePicker alloc] init];
    _selectDatePicker.isBeforeTime = YES;
    _selectDatePicker.datePickerMode = UIDatePickerModeDate;
    
    __weak typeof(self) weakSelf = self;
    [_selectDatePicker didFinishSelectedDate:^(NSDate *selectedDate) {
//        NSString *string = [NSString stringWithFormat:@"%@",[NSDate dateWithTimeInterval:3600*8 sinceDate:selectedDate]];
//        weakSelf.myLabel2.text = string;
      NSString *string = [weakSelf dateStringWithDate:selectedDate DateFormat:@"yyyy年MM月dd日"];
        _timeafterstring = string;
      [weakSelf.button2 setTitle:[NSString stringWithFormat:@"到%@",string] forState:UIControlStateNormal];
    }];

}
- (NSString *)dateStringWithDate:(NSDate *)date DateFormat:(NSString *)dateFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    NSString *str = [dateFormatter stringFromDate:date];
    return str ? str : @"";
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{



if (indexPath.row<=6) {
    return 44 ;
}else{
return 84;
}
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
//if (textView == _beifenField||textView == _TextField1||textView == _dayField) {
//    [UIView animateWithDuration:0.2 animations:^{
//    self.view.transform = CGAffineTransformMakeTranslation(0, -100);
//    }];
//
//}
UIView *view = textView.superview;

while (![view isKindOfClass:[UITableViewCell class]]) {

view = [view superview];

}

UITableViewCell *cell = (UITableViewCell*)view;

CGRect rect = [cell convertRect:cell.frame toView:self.view];

if (rect.origin.y / 2 + rect.size.height>=KScreenHeight-216-46-64-47) {

self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 216, 0);

[self.tableView scrollToRowAtIndexPath:[self.tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

}





  
    return YES;
}


- (void)textViewDidEndEditing:(UITextView *)textView{
//self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);

//if (textView == _beifenField||textView == _TextField1||textView == _dayField) {
        [UIView animateWithDuration:0.2 animations:^{
         self.view.transform = CGAffineTransformIdentity;
    }];

//}
    
   
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [_TextField1 resignFirstResponder];
    
    [_beifenField resignFirstResponder];
    
    [self.view endEditing:YES];
    return YES;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

 [UIView animateWithDuration:0.2 animations:^{
         self.view.transform = CGAffineTransformIdentity;
    }];
    return YES;
}


@end
